package com.hw.service.sys;

import cn.hutool.core.img.ImgUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hw.common.CommonConst;
import com.hw.entity.bo.tree.SysMenuTreeBO;
import com.hw.entity.dto.sys.UserInfoDTO;
import com.hw.entity.po.sys.SysMenu;
import com.hw.entity.po.sys.SysPermission;
import com.hw.entity.po.sys.SysRole;
import com.hw.entity.po.sys.SysUser;
import com.hw.entity.vo.sys.SysPermissionVO;
import com.hw.entity.vo.sys.SysRoleVO;
import com.hw.entity.vo.sys.UserInfoVO;
import com.hw.entity.vo.sys.UserSimpleInfoVO;
import com.hw.mapper.sys.SysUserMapper;
import com.hw.utils.AdminUtils;
import com.hw.utils.JwtUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 系统用户
 *
 * @author whw
 * @date 2021/6/15
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    @Autowired
    SysRoleService sysRoleService;

    @Autowired
    SysPermissionService sysPermissionService;

    @Autowired
    SysMenuService sysMenuService;

    @Override
    public SysUser getOne(String username) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("c_deleted", 0)
                .eq("c_username", username);
        return getOne(wrapper);
    }

    @Override
    public UserInfoVO getInfo() {
        String token = SecurityUtils.getSubject().getPrincipal().toString();
        UserInfoVO userInfoVo = new UserInfoVO();
        String username = JwtUtils.getClaim(token, "username");
        SysUser sysUser = getOne(username);
        BeanUtils.copyProperties(sysUser, userInfoVo);

        // 处理头像
        if (ArrayUtils.isNotEmpty(sysUser.getAvatar())) {
            String avatarBase64 = ImgUtil.toBase64(ImgUtil.toImage(sysUser.getAvatar()), "png");
            userInfoVo.setAvatar(avatarBase64);
        }

        // 获取角色
        List<SysRoleVO> roleVos = null;
        List<SysRole> roles = sysRoleService.list(username);
        if (CollectionUtils.isNotEmpty(roles)) {
            roleVos = roles.stream().map(item -> {
                SysRoleVO roleVo = new SysRoleVO();
                BeanUtils.copyProperties(item, roleVo);
                return roleVo;
            }).collect(Collectors.toList());

            // 获取权限
            List<SysPermissionVO> permissionVos = null;
            List<String> roleIds = roles.stream().map(SysRole::getRoleId).collect(Collectors.toList());
            List<SysPermission> permissions = sysPermissionService.list(roleIds);
            if (CollectionUtils.isNotEmpty(permissions)) {
                permissionVos = permissions.stream().map(item -> {
                    SysPermissionVO permissionVo = new SysPermissionVO();
                    BeanUtils.copyProperties(item, permissionVo);
                    return permissionVo;
                }).collect(Collectors.toList());

                // 获取菜单
                List<String> permissionIds = permissions.stream()
                        .filter(item -> CommonConst.PERMISSION_TYPE_MENU == item.getType())
                        .map(SysPermission::getPermissionId)
                        .collect(Collectors.toList());
                List<SysMenu> menus = sysMenuService.list(permissionIds);
                if (CollectionUtils.isNotEmpty(menus)) {
                    List<SysMenuTreeBO> menuTree = sysMenuService.getTree(menus);
                    userInfoVo.setMenus(menuTree);
                }
            }
            userInfoVo.setPermissions(permissionVos);
        }
        userInfoVo.setRoles(roleVos);

        return userInfoVo;
    }

    @Override
    public UserSimpleInfoVO getSimpleInfo() {
        String token = SecurityUtils.getSubject().getPrincipal().toString();
        UserSimpleInfoVO userInfoVo = new UserSimpleInfoVO();
        String username = JwtUtils.getClaim(token, "username");
        SysUser sysUser = getOne(username);
        BeanUtils.copyProperties(sysUser, userInfoVo);

        // 处理头像
        if (ArrayUtils.isNotEmpty(sysUser.getAvatar())) {
            String avatarBase64 = ImgUtil.toBase64(ImgUtil.toImage(sysUser.getAvatar()), "png");
            userInfoVo.setAvatar(avatarBase64);
        }
        return userInfoVo;
    }

    @Override
    public void save(UserInfoDTO dto) {
        SysUser sysUser = getById(dto.getId());
        BeanUtils.copyProperties(dto, sysUser);
        saveOrUpdate(sysUser);
    }

    @Override
    public void updateAvatar(MultipartFile file) {
        try {
            SysUser sysUser = getOne(AdminUtils.getUserName());
            byte[] bytes = file.getBytes();
            UpdateWrapper<SysUser> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("c_avatar", bytes)
                    .eq("c_user_id", sysUser.getUserId());
            update(updateWrapper);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存用户信息
     *
     * @param nickName
     */
    @Override
    public void save(String nickName) {
        SysUser sysUser = getOne(AdminUtils.getUserName());
        UpdateWrapper<SysUser> updateWrapper = new UpdateWrapper<>();
        updateWrapper
                .set("c_nickName", nickName)
                .eq("c_user_id", sysUser.getUserId());
        try {
            update(updateWrapper);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
